package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.wemedia.dtos.WmUserDto;
import com.usian.model.wemedia.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult insert(WmUser wmUser) {
        //1.参数检查
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存
        save(wmUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public List<WmUser> findByName(String name) {
        if (StringUtils.isNotBlank(name)){
            LambdaQueryWrapper<WmUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmUser::getName,name);
            return list(lambdaQueryWrapper);
        }
        return null;
    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        //1. 参数校验
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"密码不能为空");
        }
        QueryWrapper<WmUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(WmUser::getName,dto.getName());

        List<WmUser> list = list(wrapper);
        if (list!=null && list.size()==1){
            WmUser adUser = list.get(0);
            //给密码加盐salt
            String password = DigestUtils.md5DigestAsHex((dto.getPassword()+adUser.getSalt()).getBytes());
            if (adUser.getPassword().equals(password)){
                Map<String , Object> map = Maps.newHashMap();
                //为了保护用户的隐私，将存在的用户的 密码 和 salt 封装返回结果为空
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
    }
}
